package com.vrsys.service;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.vrsys.domain.LineItem;
import com.vrsys.domain.Order;
import com.vrsys.domain.session.Account;
import com.vrsys.domain.session.Cart;
import com.vrsys.persistence.LineItemMapper;
import com.vrsys.persistence.OrderMapper;
import com.vrsys.util.SID;
import com.vrsys.view.PageQuery;

@Service
public class OrderService extends BaseService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private LineItemMapper lineItemMapper;

    @Transactional(isolation=Isolation.READ_COMMITTED, rollbackFor=Throwable.class)
    public Order saveOrder(List<LineItem> lineItems, BigDecimal amount, Account account) {
        Order order = new Order();
        order.setLines(lineItems);
        order.setAmount(amount);
        order.setUserId(account.getUserId());
        order.setOrderCreateTime(Calendar.getInstance().getTime());
        order.setOrderNo(SID.nextId(17));
        orderMapper.saveOrder(order);

        for(LineItem item : lineItems) {
            item.setOrderId(order.getOrderId());
            item.setTotalPrice(item.getProduct().getUnitPrice().multiply(new BigDecimal(item.getProductQty(), Cart.mc)));
        }
        lineItemMapper.saveLineItems(order.getLines());
        return order;
    }

    public PageQuery<Order> pagingHistoryOrders(PageQuery<Order> pageQuery, Account account) {
        pageQuery.setData(orderMapper.queryHistoryOrdersPage(pageQuery,account.getUserId()));
        return pageQuery;
    }

    public List<Integer> queryOrderIds(Account account) {
        return orderMapper.getOrderIds(account.getUserId());
    }
}
